package com.hmdp.utils;


import cn.hutool.core.lang.UUID;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;

import java.util.Collections;
import java.util.concurrent.TimeUnit;

public class SimpleRedisLock implements ILock {

    private StringRedisTemplate stringRedisTemplate;
    private String name;

    public SimpleRedisLock(StringRedisTemplate stringRedisTemplate,String name){
        this.stringRedisTemplate = stringRedisTemplate;
        this.name = name;
    }

    //lua脚本
    private static final DefaultRedisScript<Long> unlockScript;
    static {
        unlockScript = new DefaultRedisScript<>();
        unlockScript.setLocation(new ClassPathResource("unLock.lua"));
        unlockScript.setResultType(Long.class);
    }

    //锁的前缀
    private static final String KEY_PREFIX = "lock:";
    //线程标识前缀
    private static final String ID_PREFIX = UUID.randomUUID().toString(true)+"-";

    @Override
    public boolean tryLock(long timeoutSec) {
        //获取线程标识
        String threadId = ID_PREFIX + Thread.currentThread().getId();
        //获取锁
        Boolean b = stringRedisTemplate.opsForValue()
                .setIfAbsent(KEY_PREFIX + name, threadId, timeoutSec, TimeUnit.SECONDS);
        return Boolean.TRUE.equals(b);//如果是true,则返回true,否则返回false 巧妙
    }

    @Override
    public void unlock() {
        //调用lua脚本
        stringRedisTemplate.execute(
                unlockScript,
                Collections.singletonList(KEY_PREFIX + name),
                ID_PREFIX + Thread.currentThread().getId()
        );
    }

    /*@Override
    public void unlock() {
        //获当前锁的线程标识
        String threadId = stringRedisTemplate.opsForValue().get(KEY_PREFIX + name);
        //获取自己的线程标识
        String id = ID_PREFIX + Thread.currentThread().getId();
        //判断是否是自己的线程标识
        if(id.equals(threadId)){
            stringRedisTemplate.delete(KEY_PREFIX + name);
        }
    }*/
}
